<?php
/**
 * Created by PhpStorm.
 * User: Yieong
 * Date: 14-9-28
 * Time: 上午10:17
 */

class PubFunc {
	
    public static function huanBi($current, $last){
        if(empty($last)){
            $data = 0;
        }else if(empty($current)){
            $data = -100;
        }else{
            $data = round(($current - $last)/$last*100,2);
        }

        return floatval($data);
    }

    public static function isAjax(){
        return (!empty($_REQUEST['__isAjax']) || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == strtolower('XMLHttpRequest')));
    }

    /**
     * 判断是否是手游游戏/平台
     * @param $platform
     * @param string $for       g为查游戏，p为查平台
     */
    public static function isMobile($key, $for='g'){
        if(empty($key)) return false;

        if($for != 'g'){
            $dict = PubAuth::getMyPlatformList();
            return isset($dict[$key]['PlatformType']) ? ($dict[$key]['PlatformType'] == 2) : false;
        }else{
            $dict = PubAuth::getMyGameList();
            return isset($dict[$key]['GameType']) ? ($dict[$key]['GameType'] == 2) : false;
        }
    }

    public static function t($message, $category='base', $params=array(),$source=null,$language=null){
        return Yii::t($category, $message, $params, $source, $language);
    }

    public static function checkEmpty($arr, $columns){
        $result = false;
        foreach($columns as $v){
            if(empty($arr[$v])){
                $result = true;
                break;
            }
        }
        return $result;
    }
    
    public static function getLastDay($yyyymm){
    	$yyyymm += '-01';
    	return date('Y-m-d', strtotime('-1 day', strtotime('+1 month', strtotime($yyyymm))));
    }

    /**
     * 获得随机字符串
     * @param type $len     需要的长度
     * @return string       返回随机字符串
     */
    public static function getRandomText($len, $special=true){
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if($special){
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);
        $str = '';
        for($i=0; $i<$len; $i++){
            $str .= $chars[mt_rand(0, $charsLen)];
        }
        return $str;
    }

    public static function getUrl($folder, $control, $action){
        return "/{$folder}/?r={$control}/{$action}";
    }

    public static function parseDict(&$array,$dict = array()){
        foreach($array as &$item){
            foreach($dict as $k => $v){
                if(array_key_exists($k,$item)){
                    $item[$k] = $v[$item[$k]] ? $v[$item[$k]] : $item[$k];
                }
            }
        }
        unset($item);
    }

    public static function defaultValue($value,$default = ""){
        return $value ? $value : $default;
    }

    public static function parseString($str,$params,$split = "#"){
        foreach($params as $k => $v){
            $str = str_replace($split . $k . $split, $v,$str);
        }
        return $str;
    }

    public static function getDbName($platform, $game){
        return 'R2MgmtDB_'.strtoupper($game);
    }

    public static function ajaxUrl($url, $params){
    	
    	if ($params['p'] == 'en') {
    		$params['p'] = 'r2games';
    	}

        $params['__isAjax'] = 1;
        if(strpos($url, '?') === false){
            $url .= '?'.http_build_query($params);
        }else{
            $url .= '&'.http_build_query($params);
        }
        return $url;
    }

    public static function getLimit($length, $page){
        if(empty($length) || empty($page)) return "";

        $index  = $length * ($page - 1);
        $length = intval($length);

        return "LIMIT {$index}, {$length}";
    }

    public static function getOrder($order, $sort = 'asc'){
        $order = $order;
        if(!in_array($sort, array('asc', 'desc'))) $sort = 'asc';

        return "ORDER BY {$order} {$sort}";
    }

    public static function request($url, $data = array(), $timeout = 30, $hostIp = '', $userHeader = array(), $proxy = '', $isCookie = false)
    {
        $url = trim($url);
        if (empty($url)) {
            return array('code' => '0');
        }
        $curl = curl_init();
        $header = array(
            'Accept-Language: zh-cn',
            'Connection: Keep-Alive',
            'Cache-Control: no-cache'
        );

        if (!empty($hostIp)) {
            $urlInfo = parse_url($url);
            $url = str_replace($urlInfo['host'], $hostIp, $url);
            $header[] = "Host: {$urlInfo['host']}";
        }
        if ($userHeader) {
            $header = array_merge($header, $userHeader);
        }

        if ($proxy) {
            curl_setopt($curl, CURLOPT_PROXY, $proxy);
        }

        if ($isCookie) {
            curl_setopt($curl, CURLOPT_COOKIEFILE, '/tmp/curl_cookie.txt');
            curl_setopt($curl, CURLOPT_COOKIEJAR, '/tmp/curl_cookie.txt');
        }

        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($curl, CURLOPT_POST, true);
        }

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_USERAGENT, 'QF 1.0.0 (curl) ');
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if ($timeout > 0) {
            curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
        }

        curl_setopt($curl, CURLINFO_HEADER_OUT, true);//header

        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
        curl_setopt($curl, CURLOPT_AUTOREFERER, true);//自动跳转


        $isPost = false;
        $isFile = false;
        if (!empty($data)) {
            $isPost = true;
        }
        if(!empty($files)){
            foreach($files as $name => $file){
                $data[$name] = curl_file_create(realpath($file['path']), $file['type'], $file['name']);
            }
            $isPost = false;
            $isFile = true;
        }


        if($isPost){
            curl_setopt($curl, CURLOPT_POST, true);//这玩意一定要写在CURLOPT_POSTFIELDS前面
            if(is_array($data)) $data = http_build_query($data);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        if($isFile){
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }

        $result['result'] = curl_exec($curl);
        $responseHeader = '';

        $result['code'] = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        if ($result['result'] === false) {
            $result['result'] = curl_error($curl);
            $result['code'] = -curl_errno($curl);
        }

        curl_close($curl);
        return $result;
    }

    public static function log($file, $content){
        $path = Yii::getPathOfAlias('docroot') . "/logs/";

        if(!is_dir($path)) mkdir($path, 0777, true);

        file_put_contents($path . $file, '['.date('Y-m-d H:i:s').']'.$content . PHP_EOL,FILE_APPEND);
    }

    public static function getRecDate($period, $begin, $end){
        $period = strtolower($period);

        $array      = array();
        $beginTime  = strtotime($begin);
        $endTime    = strtotime($end);

        switch($period){
            case 'weekly':
                for(;$beginTime<=$endTime;$beginTime+=86400){
                    if(date('w',$beginTime) == 1){
                        $array[] = date('Y-m-d', $beginTime);
                    }
                }

                break;
            case 'monthly':
                for(;$beginTime<=$endTime;$beginTime+=86400){
                    if(date('d',$beginTime) == 1){
                        $array[] = $date = date('Y-m-d', $beginTime);;
                    }
                }

                break;
        }

        return $array;
    }

    public static function addTip($class, $headerArr, $prefix="", $suffix=""){
        $icon = ' <i class="fa fa-question-circle" style="color: #993333;"></i>';

        foreach($headerArr as $k=>&$v){
            if(isset($v['include'])){
                foreach($v['include'] as $kk=>&$vv){
                    if(!isset($vv['tips'])){
                        $key = ($prefix ? "{$prefix}-" : "")."{$class}-{$kk}".($suffix ? "-{$suffix}" : "");
                        $vv['tips'] = PubFunc::t($key, 'tips');
                        $vv['text'] .= $icon;
                    }
                }
            }else{
                if(!isset($v['tips'])){
                    $key = ($prefix ? "{$prefix}-" : "")."{$class}-{$k}".($suffix ? "-{$suffix}" : "");
                    $v['tips'] = PubFunc::t($key, 'tips');
                    $v['text'] .= $icon;
                }
            }
        }
        return $headerArr;
    }

    public static function getTip($headerArr){
        $result = array();
        foreach($headerArr as $k=>$v){
            if(!PubFunc::checkEmpty($v, array('text', 'tips')))
                $result[] = array('name' => $v['text'], 'desc' => $v['tips']);

            if(isset($v['include'])){
                foreach($v['include'] as $kk=>$vv){
                    if(!PubFunc::checkEmpty($vv, array('text', 'tips')))
                        $result[] = array('name' => "{$v['text']} - {$vv['text']}", 'desc' => $vv['tips']);
                }
            }
        }

        return $result;
    }

    public static function dict($type){
        $model = new ModDict();
        return $model->getDict($type);
    }

    public static function upload($action, $config=''){
        $defConf = array (
            // 上传图片配置
            'imageActionName' => 'uploadimage',
            'imageFieldName' => 'upfile',
            'imageMaxSize' => 2048000,
            'imageAllowFiles' => array ('.png', '.jpg', '.jpeg', '.gif', '.bmp'),
            'imageCompressEnable' => true,
            'imageCompressBorder' => 1600,
            'imageInsertAlign' => 'none',
            'imageUrlPrefix' => '',
            'imagePathFormat' => '/public/uploads/ueditor/image/{yyyy}{mm}{dd}/{time}{rand:6}',

            // 上传文件配置
            'fileActionName' => 'uploadfile',
            'fileFieldName' => 'upfile',
            'fileMaxSize' => 512000000,
            'fileUrlPrefix' => '',
            'fileAllowFiles' => array(
                ".png", ".jpg", ".jpeg", ".gif", ".bmp",
                ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
                ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
                ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso", ".csv",
                ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
            ),
            'filePathFormat' => '/public/uploads/ueditor/file/{yyyy}{mm}{dd}/{time}{rand:6}',

            // 列出图片列表配置
            'imageManagerActionName'    => 'listimage',
            'imageManagerListPath'      => '/public/uploads/ueditor/image/',
            'imageManagerListSize'      => 20,
            'imageManagerUrlPrefix'     => '',
            'imageManagerInsertAlign'   => 'none',
            'imageManagerAllowFiles'    => array(".png", ".jpg", ".jpeg", ".gif", ".bmp"),

            // 列出文件列表配置
            'fileManagerActionName'     => 'listfile',
            'fileManagerListPath'       => '/public/uploads/ueditor/file/',
            'fileManagerListSize'       => 20,
            'fileManagerUrlPrefix'      => '',
            'fileManagerAllowFiles'     => array(
                ".png", ".jpg", ".jpeg", ".gif", ".bmp",
                ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
                ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
                ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso", ".csv",
                ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
            ),

        );
        $config = array_merge($defConf, $config);

        $result = false;
        if($action == 'config'){
            $result = $config;
        } else {
            $mission = '';

            switch($action){
                case 'uploadimage':
                    $mission = 'upload';
                    $config  = array(
                        "pathFormat"    => $config['imagePathFormat'],
                        "maxSize"       => $config['imageMaxSize'],
                        "allowFiles"    => $config['imageAllowFiles']
                    );
                    break;
                case 'uploadfile':
                    $mission = 'upload';
                    $config  = array(
                        "pathFormat"    => $config['filePathFormat'],
                        "maxSize"       => $config['fileMaxSize'],
                        "allowFiles"    => $config['fileAllowFiles']
                    );
                    break;
                case 'listfile':
                    $mission = 'list';
                    $config  = array(
                        "allowFiles"    => $config['fileManagerAllowFiles'],
                        "listSize"      => $config['fileManagerListSize'],
                        "path"          => $config['fileManagerListPath']
                    );
                    break;
                case 'listimage':
                    $mission = 'list';
                    $config  = array(
                        "allowFiles"    => $config['imageManagerAllowFiles'],
                        "listSize"      => $config['imageManagerListSize'],
                        "path"          => $config['imageManagerListPath']
                    );
                    break;
            }

            if($mission == 'upload'){
                /* 生成上传实例对象并完成上传 */
                $up = new PubUeUploader('upfile', $config, 'upload');
                /* 返回数据 */
                $result = $up->getFileInfo();
            }else if($mission == 'list'){
                $list = new PubUeLister($config);

                $result = $list->getList();
            }
        }

        return $result;
    }

    public static function setTimeZone($platform){
        $timeZone = Yii::app()->params['TimeZone'];

        if(isset($timeZone[$platform])){
            date_default_timezone_set($timeZone[$platform]);
        }
    }

    public static function getMultiApp(){
        $platform = PubAcc::getMyPlatformList();

        $app = array(
            'oss' => array(
                'r2games'   => array(
                    'AppName' => '英语',
                    'AppNameEn' => 'English',
                    'AppUrl' => 'http://oss.r2games.com/oss/'
                ),
                'fr'        => array(
                    'AppName' => '法语',
                    'AppNameEn' => 'French',
                    'AppUrl' => 'http://fross.r2games.com/oss/'
                ),
                'de'        => array(
                    'AppName' => '德语',
                    'AppNameEn' => 'German',
                    'AppUrl' => 'http://deoss.r2games.com/oss/'
                ),
                'br'        => array(
                    'AppName' => '葡萄牙语',
                    'AppNameEn' => 'Portuguese',
                    'AppUrl' => 'http://bross.r2games.com/oss/'
                ),
                'tr'        => array(
                    'AppName' => '土耳其语',
                    'AppNameEn' => 'Turkish',
                    'AppUrl' => 'http://tross.r2games.com/oss/'
                ),
                'ru'        => array(
                    'AppName' => '俄语',
                    'AppNameEn' => 'Russian',
                    'AppUrl' => 'http://ruoss.r2games.com/oss/'
                ),
                'mobile'   => array(
                    'AppName' => '手游',
                    'AppNameEn' => 'Mobile',
                    'AppUrl' => 'http://oss.r2games.com/oss/'
                ),
            )
        );

        foreach($app as &$v){
            foreach($v as $kk=>$vv){
                if(!isset($platform[$kk])){
                    unset($v[$kk]);
                }
            }
        }
        unset($v);

        return $app;
    }

    public static function dictCountryAbbr(){
        return (new ModDict())->getDictCountryAbbr();
    }

    public static function getDepth(&$arr, $root, $idColumn, $pidColumn, $first=true){
        if(isset($arr[$root]) || $first){
            $depth = isset($arr[$root]['Depth']) ? $arr[$root]['Depth'] + 1 : 1;

            foreach($arr as &$v){
                if($v[$pidColumn] == $root){
                    $v['Depth'] = $depth;
                    PubFunc::getDepth($arr, $v[$idColumn], $idColumn, $pidColumn, false);
                }
            }
        }else{
            return;
        }
    }


    public static function addBy(&$the){
        $me = AccAuth::me();
        if(is_object($the)){
            $the->AddBy     = $me['UserID'];
            $the->AddTime   = date('Y-m-d H:i:s');
        }else if(is_array($the)){
            $the['AddBy']   = $me['UserID'];
            $the['AddTime'] = date('Y-m-d H:i:s');
        }
    }

    public static function editBy(&$the){
        $me = AccAuth::me();
        if(is_object($the)){
            $the->EditBy     = $me['UserID'];
            $the->EditTime   = date('Y-m-d H:i:s');
        }else if(is_array($the)){
            $the['EditBy']   = $me['UserID'];
            $the['EditTime'] = date('Y-m-d H:i:s');
        }
    }

    public static function buildUrl($url, $menuId=null){
        $params = array(
            'm' => isset($menuId) ? $menuId : PubRequest::R('m'),
            'p' => PubRequest::R('p'),
            'g' => PubRequest::R('g')
        );
        return $url . ((strpos($url, '?')) ? '&' : '?') . http_build_query($params);
    }
    
    /**
     * 编辑返回组成的路径方法
     * @param unknown $url
     * $type = 2 出现在页面只剩下一条数据，删除成功之后需要返回上一页的数据，因为当前页已经没有数据可以显示了
     * @return string
     */
    public static function buildBackUrl($url,$type = 1){
    	$page = PubRequest::R('page');
    	if($type == 2){   		
    		$page = $page -1;
    	}
    	$params = array(   		
    		'g'    => PubRequest::R('g'),
    	    'm'    => PubRequest::R('m'),
    		'page' => $page,
    	);  	
    	return $url . ((strpos($url, '?')) ? '&' : '?') . http_build_query($params);
    }
    
}